package com.chatsocket.socketServlet;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chatsocket.util.Constant;
import com.chatsocket.util.User;
@ServerEndpoint(value="/websocket/{userId}/{sessionId}",configurator=HttpSocketConfig.class)
public class WebSocketServlet{
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private Long userId;
    private final static String WEB_SOCKET_FLAG="_cc_websockect_";
    private User user;
    private String httpSessionId;
    
    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId,@PathParam("sessionId") String sessionId,EndpointConfig config){
//    	HttpSession httpSession = (HttpSession)config.getUserProperties().get("httpSession");
    	//FIXME 保存httpSessionId
    	this.userId=Long.parseLong(userId);
    	this.user=Constant.getUser(Long.parseLong(userId));
    	this.httpSessionId=sessionId;
    	Constant.webSocketMap.put(userId,this);
    	CopyOnWriteArraySet<WebSocketServlet> set = Constant.webSocketSetMap.get(userId);
    	if(set==null){
    		set=new CopyOnWriteArraySet<WebSocketServlet>();
    	}
    	set.add(this);
    	Constant.webSocketSetMap.put(user.getUserType()+"_"+userId, set);
        this.session = session;
    }
     
    /**
     * 连接关闭调用的方法
     * 从webSocket池中删除该webSocket
     */
    @OnClose
    public void onClose(){
    	CopyOnWriteArraySet<WebSocketServlet> set = Constant.webSocketSetMap.get(user.getUserType()+"_"+userId);
    	if(set!=null){
    		for(WebSocketServlet webSocket:set){
    			Session sessionId = webSocket.getSession();
    			if(this.session==sessionId){
    				//重写equals 会更好
    				set.remove(webSocket);
    				break;
    			}
    		}
    	}
    }
     
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        JSONObject jsonObject = JSON.parseObject(message);
        String msg = jsonObject.getString("msg");
        String tarUserName = jsonObject.getString("tarUserName");
        WebSocketServlet webSocketServlet = Constant.webSocketMap.get(tarUserName);
        try {
			webSocketServlet.sendMessage(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
     
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }
     
    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }
	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public Session getSession() {
		return session;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public static String getWebSocketFlag() {
		return WEB_SOCKET_FLAG;
	}

	public String getHttpSessionId() {
		return httpSessionId;
	}

	public void setHttpSessionId(String httpSessionId) {
		this.httpSessionId = httpSessionId;
	}
}
